package config

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"kim/model"
	"time"
)

func NewRouter() *gin.Engine {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{ // type H map[string]interface{}
			"message": "pong",
		})
	})

	return r
}

var DB *gorm.DB

// 执行数据库初始化  华为kim
func init() {
	db, err := gorm.Open("mysql", "root:Qq761090@(122.9.162.21:3306)/kim?charset=utf8&parseTime=true")
	if err != nil {
		fmt.Println("connect err:", err)
	}
	db.LogMode(true)
	if err != nil {
		panic(err)
	}
	if gin.Mode() == "release" {
		db.LogMode(false)
	}
	db.SingularTable(true)       //默认不加复数s
	db.DB().SetMaxIdleConns(20)  //设置连接池，空闲
	db.DB().SetMaxOpenConns(100) //设置打开最大连接
	db.DB().SetConnMaxLifetime(time.Second * 30)

	//自动迁移 完成建表
	db.AutoMigrate(&model.User{}, &model.Community{}, &model.Contact{}, &model.Relation{}, &model.OffRecord{})

	DB = db
	fmt.Println("完成数据库连接初始化")
	fmt.Println(DB)
	mongoDBInit()

}

var MongoDBClient *mongo.Client

func mongoDBInit() {

	clientOptions := options.Client().ApplyURI("mongodb://47.108.105.87:27017")
	var err error
	MongoDBClient, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		fmt.Println(err)
	}

	err = MongoDBClient.Ping(context.TODO(), nil)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("MongoDB 连接建立成功")

}
